<template>
  <el-select ref="zSelect" :value="keyword" @clear="handleClear" v-bind="$attrs" v-on="$listeners">
    <el-option value="" hidden></el-option>
    <div class="z-container">
      <div class="z-choose-year">
        <i class="el-icon-arrow-left arrow-icon" @click="handleChangeTargetYear('subtract')"></i>
        <div>{{ targetYear.year() }}</div>
        <i class="el-icon-arrow-right arrow-icon" @click="handleChangeTargetYear('add')"></i>
      </div>
      <div class="z-quarter-cover">
        <div class="z-quarter-cover-item" v-for="(item,index) in quarterList" :key="index"
             :class="{'active': active === item.value}"
             @click="handleClickQuarterItem(item)">{{ item.label }}
        </div>
      </div>
    </div>
  </el-select>
</template>

<script>
import dayjs from '@/plugins/dayjs'

export default {
  name: "QuarterSelector",
  props: {
    value: Array
  },
  data() {
    return {
      keyword: '',
      targetYear: dayjs(),
      quarterList: [{
        value: '1',
        label: '第一季度'
      }, {
        value: '2',
        label: '第二季度'
      }, {
        value: '3',
        label: '第三季度'
      }, {
        value: '4',
        label: '第四季度'
      }],
      active: null
    }
  },
  watch: {
    value: {
      handler(val, oldVal) {
        if (JSON.stringify(val) === JSON.stringify(oldVal)) return
        if (val instanceof Array && val.length === 2) {
          this.targetYear = this.targetYear.year(val[0])
          this.active = val[1].toString()
          this.setKeyword()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    setKeyword(year = this.targetYear.year()) {
      const target = this.quarterList.find((i) => i.value === this.active)
      this.keyword = `${year}年 ${target?.label ?? ''}`
      this.$emit('input', [this.targetYear.year().toString(), target.value])
    },
    handleChangeTargetYear(mode) {
      this.targetYear = this.targetYear[mode](1, 'year')
      this.setKeyword()
    },
    handleClickQuarterItem(item) {
      this.active = item.value
      this.setKeyword()
      this.$refs.zSelect.visible = false
    },
    handleClear() {
      this.keyword = ''
      this.$emit('input', [])
    }
  }
}
</script>

<style scoped lang="scss">
.z-container {
  width: 100%;

  .z-choose-year {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 40px;

    .arrow-icon {
      margin: 0 30px;
      padding: 0 5px;
      cursor: pointer;
    }
  }

  .z-quarter-cover {
    width: 100%;

    &-item {
      width: 100%;
      height: 40px;
      line-height: 40px;
      text-align: center;
      cursor: pointer;
    }

    .active {
      background: #f5f5f5;
    }
  }
}
</style>
